use actix_web::http::header::{ContentEncoding, ContentType};
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder, ResponseError, Result};
use serde::Serialize;
use std::io;

// 构建器模式创建HTTP响应
async fn index() -> HttpResponse {
    HttpResponse::Ok()
        .content_type(ContentType::plaintext())
        .insert_header(("X-Hdr", "simple"))
        .body("data")
}

#[derive(Serialize)]
struct MyObj {
    name: String,
}

#[get("/a/{name}")]
async fn index2(name: web::Path<String>) -> Result<impl Responder> {
    let obj = MyObj {
        name: name.into_inner(),
    };
    Ok(web::Json(obj))
}

#[get("/index3")]
async fn index3() -> HttpResponse {
    HttpResponse::Ok()
        // 表示禁用内容压缩
        .insert_header(ContentEncoding::Identity)
        .body("data")
}

static HELLO_WORLD: &[u8] = &[
    0x1f, 0x8b, 0x08, 0x00, 0xa2, 0x30, 0x10, 0x5c, 0x00, 0x03, 0xcb, 0x48, 0xcd, 0xc9, 0xc9,
    0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0xe1, 0x02, 0x00, 0x2d, 0x3b, 0x08, 0xaf, 0x0c, 0x00,
    0x00, 0x00,
];

#[get("/index4")]
async fn index4() -> HttpResponse {
    HttpResponse::Ok()
        .insert_header(ContentEncoding::Gzip)
        .body(HELLO_WORLD)
}

#[actix_web::main]
async fn main() -> io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/index", web::get().to(index))
            .service(index2)
            .service(index4)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
